package observer.plan_2;

/**
 * @author chenyuan
 * @date 2020/10/30 9:28
 */

import observer.plan_1.CurrentConditions;

import java.util.ArrayList;

/**
 * 包含最新的天气信息
 * 包含 观察者集合
 * 当数据有更新时，遍历观察者集合，通知所有的观察者
 */
public class WeatherData implements Subject{
    private float temperatrue;
    private float pressure;
    private float humidity;
    // 观察者集合
    private ArrayList<Observer> observers;

    public WeatherData() {
        observers = new ArrayList<Observer>();
    }

    public float getTemperature() {
        return temperatrue;
    }

    public float getPressure() {
        return pressure;
    }

    public float getHumidity() {
        return humidity;
    }

    // 当数据有更新时，就调用该方法
    public void setData(float temperature, float pressure, float humidity) {
        this.temperatrue = temperature;
        this.pressure = pressure;
        this.humidity = humidity;
        // 将最新的信息推送给 观察者
        notifyObservers();
    }

    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    public void removeObserver(Observer observer) {
        if (observers.contains(observer)){
            observers.remove(observer);
        }
    }

    public void notifyObservers() {
        for (int i = 0; i < observers.size(); i++) {
            observers.get(i).update(getTemperature(), getPressure(), getHumidity());
        }
    }
}
